package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.bp_history

import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.interstitial.api.ATInterstitial
import com.anythink.nativead.api.ATNativeAdView
import com.anythink.nativead.api.ATNativePrepareExInfo
import com.anythink.nativead.api.ATNativePrepareInfo
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.listener.manual_load.TopOnInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.SelfRenderViewUtil
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdManager
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseActivity
import com.bp.hearthealth.pulse.lnapps.databinding.ActivityBloodPressureHistoryListBgBinding
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.BpBloodPressureViewModel
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.bp_report.BloodPressureResultActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_dialog.CalendarDialog
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DateUtils
import com.bp.hearthealth.pulse.lnapps.bp_utils.DoubleClickListener
import com.bp.hearthealth.pulse.lnapps.bp_utils.throttleClick
import com.bp.hearthealth.pulse.lnapps.bp_view.BPSpacingItemDecoration
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import com.isnoam.calendar.bean.DateInfo
import org.koin.androidx.viewmodel.ext.android.viewModel

class BpBloodPressureHistoryListActivity :
    BpBaseActivity<ActivityBloodPressureHistoryListBgBinding>() {

    private var nativeAd: NativeAd? = null
    private val viewModel: BpBloodPressureViewModel by viewModel()
    private val bloodPressureHistoryListAdapter = BpBloodPressureHistoryListAdapter()
    private var view: View? = null
    private var calendarDialog: CalendarDialog? = null
    private var chooseOne = false//true:选择某一天, false:选择时间范围  默认30天的数据
    private var topOnNativeAd: com.anythink.nativead.api.NativeAd? = null

    override fun initData() {
        super.initData()
        registerObserver()
        binding.viewModel = viewModel
//        loadAdMobNativeAd()
        if (!AdsSwitch.getBoolean(AdsSwitch.adInterCacheControl)) {
            TopOnInterAdManager.initManualLoadInterstitialAd(this)
            TopOnInterAdManager.manualLoadAd()
        }
        loadTopOnNativeAd()
        initRecyclerView()
        initCalendarDialog()
        //血压历史页展示
        AppsFlyerUtils.trackEvent("bp_history_show")
    }

    private fun initCalendarDialog() {
        calendarDialog = CalendarDialog(this)
        //保存选择的时间范围
        calendarDialog!!.setOnBtnClickLisener(object : CalendarDialog.OnDateRangeSelectedListener {
            override fun setOnDateRangeSelectedListener(
                startDate: DateInfo, endDate: DateInfo?
            ) {
                if (endDate == null) {
                    //选择某一天
                    chooseOne = true
                    viewModel.selectedTime.value = startDate.formatAsMMMdd()
                    viewModel.startTime.value = startDate.timeInMillis()
                    //获取当天开始时间和结束时间
                    viewModel.startTime.value =
                        DateUtils.getStartAndEndOfDay(startDate.timeInMillis()).first
                    viewModel.endTime.value =
                        DateUtils.getStartAndEndOfDay(startDate.timeInMillis()).second
                    LogUtil.i("查询时间戳为：开始时间：${viewModel.startTime.value} 结束时间：${viewModel.endTime.value}")
                } else {
                    //选择的是范围
                    chooseOne = false
                    viewModel.selectedTime.value =
                        "${startDate.formatAsMMMdd()}-${endDate.formatAsMMMdd()}"
                    //开始当天-的00:00:00时间戳
                    viewModel.startTime.value =
                        DateUtils.getStartAndEndOfDay(startDate.timeInMillis()).first
                    //结束当天-的23:59:59时间戳
                    viewModel.endTime.value =
                        DateUtils.getStartAndEndOfDay(endDate.timeInMillis()).second
                    LogUtil.i("查询时间戳为：开始时间：${startDate.timeInMillis()} 结束时间：${endDate.timeInMillis()}")
                }
                viewModel.getBloodPressureDataForDateRange(Constants.USER_ID)
            }
        })
    }

    override fun initListener() {
        super.initListener()
        binding.llTime.setOnClickListener(object : DoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
                calendarDialog!!.showDialog()
            }
        })
    }

    private fun initRecyclerView() {
        binding.apply {
            val layoutManager = LinearLayoutManager(activity)
            layoutManager.orientation = LinearLayoutManager.VERTICAL
            recyclerView.layoutManager = layoutManager
            recyclerView.adapter = bloodPressureHistoryListAdapter
            val marginBottom = resources.getDimensionPixelSize(R.dimen.activity_vertical_margin)
            recyclerView.addItemDecoration(BPSpacingItemDecoration(marginBottom, 0))
            bloodPressureHistoryListAdapter.setOnItemClickLisener(object :
                BpBloodPressureHistoryListAdapter.OnItemClickListener {
                override fun onItemClick(bpdId: String, date: Long) {
                    //展示插页广告
//                    loadAdMobInsertAd(bpdId, date)
                    loadTopOnInsertAd(bpdId, date)
                }
            })
        }
    }

    private fun registerObserver() {
        viewModel.queueBloodPressureData.observe(this, Observer { result ->
            val response = result.getOrNull()
            if (response.isNullOrEmpty()) {
                bloodPressureHistoryListAdapter.setListData(emptyList(), chooseOne)
                viewModel.listSize.value = 0
                return@Observer
            }

            // 对列表按照 timePeriod 升序排序
            val sortedResponse = response.sortedBy { bloodPressure ->
                bloodPressure.bloodPressureList.minByOrNull { it.timePeriod }?.timePeriod
                    ?: Long.MAX_VALUE
            }
            viewModel.listSize.value = sortedResponse.size
            bloodPressureHistoryListAdapter.setListData(sortedResponse, chooseOne)
            LogUtil.i("数据列表为：$sortedResponse")
        })

        viewModel.listSize.observe(this) { size ->
            if (size == 0) {
                if (view != null) {
                    view!!.visibility = View.VISIBLE
                    return@observe
                }
                view = binding.viewStub.viewStub?.inflate()
            } else {
                view?.visibility = View.GONE
            }
        }
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        binding.includeToolbar.apply {
            tvBack.text = getString(R.string._history_str)
            ImmersionBar.with(this@BpBloodPressureHistoryListActivity).titleBar(toolbar).init()
            tvBack.throttleClick {
//                loadAdMobInsertAd()
                loadTopOnInsertAd()
            }
        }
    }


    /**
     * 插页广告
     *
     *  ○ 点击Back入口，展示插页广告，该条检测数据保存
     *      ■ 插页广告资源加载到，立即展示，广告关闭后自动跳转至上一级页面
     *      ■ 插页广告资源未加载到，自动跳转至上一级页面
     *
     *      空:销毁
     *      非空:跳转新activity
     */
    private fun loadAdMobInsertAd(vararg bean: Any) {
        AdMobInterstitialAdManager.setInterstitialAdListener(object : AdMobInterstitialAdListener {
            override fun onAdDismissedFullScreenContent() {
                startJumpActivity(bean)
            }

            override fun onAdFailedToShowFullScreenContent() {
                startJumpActivity(bean)
            }

            override fun onNotReady() {
                startJumpActivity(bean)
            }

            override fun onAdShowedFullScreenContent() {
                //点击返回入口后_插页广告
                ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID, "f66471fd6d9f45")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【【血压历史页点击返回入口后_插页广告】")
                AppsFlyerUtils.trackEvent("ad_inter_bp_history_back_show")
            }
        })
        AdMobInterstitialAdManager.showInterstitialAd(this)
    }

    private fun loadTopOnInsertAd(vararg bean: Any) {
        topOnNativeAd?.let { TopOnNativeAdManager.removeUsedNativeAd(it) }
        TopOnInterAdManager.setManualLoadListener(object : TopOnInterstitialAdListener {
            override fun onFireBaseAdIsClosed() {
                startJumpActivity(bean)
            }

            override fun onInterstitialAdShow(entity: ATAdInfo) {
                ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID, "f66471fd6d9f45")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【血压历史页点击返回入口后_插页广告】")
                AppsFlyerUtils.trackEvent("ad_inter_bp_history_back_show")
            }

//            override fun onInterstitialAdLoaded() {
//                LogUtil.iTopOn("插页广告 onInterstitialAdLoaded 回调")
//                if (TopOnInterAdManager.isAdReady()) {
//                    TopOnInterAdManager.mInterstitialAd!!.show(this@BpBloodPressureHistoryListActivity)
//                } else {
//                    startJumpActivity(bean)
//                }
//            }

            override fun onInterstitialAdClose(entity: ATAdInfo) {
                startJumpActivity(bean)
            }

            override fun onInterstitialAdLoadFail(adError: AdError) {
                startJumpActivity(bean)
            }

            override fun onInterstitialAdVideoError(adError: AdError) {
                startJumpActivity(bean)
            }

            override fun onNotReady() {
                startJumpActivity(bean)
            }
        })
        TopOnInterAdManager.showInterstitialAd(this)
    }


    override fun onPause() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onPause()
        }
        super.onPause()
        viewModel.stopTimer()
    }

    override fun onResume() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onResume()
        }
        super.onResume()
        viewModel.getBloodPressureDataForDateRange(Constants.USER_ID)
    }


    private fun loadTopOnNativeAd() {
        if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
            setNativeTopOnAdView()
        } else {
            TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
                override fun onNativeAdLoaded() {
                    LogUtil.iTopOn("TopOn 【原生广告】 监听，显示广告")
                    if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
                        setNativeTopOnAdView()
                    }
                }
            })
        }
    }

    private fun setNativeTopOnAdView() {
        topOnNativeAd = TopOnNativeAdManager.getNativeAds().first()
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdImpressed(view: ATNativeAdView, entity: ATAdInfo) {
                AppsFlyerUtils.trackEvent("ad_native_bp_history_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID, "f664720d037946")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【Blood Pressure History页_原生广告】")
                TopOnNativeAdManager.removeUsedNativeAdListener()
            }
        })
        binding.nativeAdView.removeAllViews()
        var mNativePrepareInfo: ATNativePrepareInfo? = null
        try {
            mNativePrepareInfo = ATNativePrepareExInfo()
            if (topOnNativeAd?.isNativeExpress == true) {
                LogUtil.iTopOn("【原生广告】 自渲染广告")
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    null
                )
            } else {
                LogUtil.iTopOn("【原生广告】 模板广告")
                SelfRenderViewUtil.bindSelfRenderView(
                    activity,
                    topOnNativeAd?.adMaterial,
                    binding.nativeSelfrenderView.root,
                    mNativePrepareInfo
                )
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    binding.nativeSelfrenderView.root
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        topOnNativeAd?.prepare(binding.nativeAdView, mNativePrepareInfo)
        binding.nativeAdView.visibility = View.VISIBLE
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdCloseButtonClick(view: ATNativeAdView, entity: ATAdInfo) {
                TopOnNativeAdManager.destroyAd()
                binding.nativeAdView.visibility = View.GONE
            }
        })
    }


    /**
     * 原生广告
     *     ■ 原生广告资源加载到，展示广告
     *     ■ 原生广告资源未加载到，隐藏广告位
     */
    private fun loadAdMobNativeAd() {
        AdMobNativeAdManager.setNativeAdListener(object : AdMobNativeAdListener {
            override fun onAdLoaded(loadedNativeAd: MutableList<NativeAd>) {
                setNativeAdView(loadedNativeAd)
            }

            override fun onAdImpression() {
                //原生广告埋点
                AppsFlyerUtils.trackEvent("ad_native_bp_history_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID, "f664720d037946")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【Blood Pressure History页_原生广告】")
                AdMobNativeAdManager.removeUsedNativeAdListener()
            }
        })
        val nativeAdList = AdMobNativeAdManager.getNativeAds()
        if (nativeAdList.isNotEmpty()) {
            setNativeAdView(nativeAdList)
        }
    }

    private fun setNativeAdView(nativeAdList: MutableList<NativeAd>) {
        nativeAd = nativeAdList.first()
        binding.nativeAdContainer.setNativeAd(nativeAd)
        binding.nativeAdContainer.visibility = View.VISIBLE
    }

    private fun startJumpActivity(bean: Array<out Any>) {
        if (bean.isEmpty()) {
            finish()
        } else {
            val intent = Intent(
                activity, BloodPressureResultActivity::class.java
            )
            intent.putExtra("type", Constants.BLOOD_PRESSURE_LIST)
            intent.putExtra("bpdId", bean[0].toString())
            intent.putExtra("date", bean[1].toString().toLong())
            startActivity(intent)
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
//        loadAdMobInsertAd()
        loadTopOnInsertAd()
    }

    override fun onDestroy() {
        super.onDestroy()
        TopOnInterAdManager.setManualLoadListener(null)
        nativeAd?.let { AdMobNativeAdManager.removeUsedNativeAd(it) }
    }
}